{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2\n",
    "%matplotlib inline\n",
    "%config InlineBackend.figure_format = 'retina'\n",
    "import warnings\n",
    "\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Introduction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from IPython.display import YouTubeVideo\n",
    "\n",
    "YouTubeVideo(id=\"uTHihJiRELc\", width=\"100%\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this chapter, we will look at the relationship between graphs and linear algebra.\n",
    "\n",
    "The deep connection between these two topics is super interesting,\n",
    "and I'd like to show it to you through an exploration of three topics:\n",
    "\n",
    "1. Path finding\n",
    "1. Message passing\n",
    "1. Bipartite projections\n",
    "\n",
    "## Preliminaries\n",
    "\n",
    "Before we go deep into the linear algebra piece though,\n",
    "we have to first make sure some ideas are clear.\n",
    "\n",
    "The most important thing that we need\n",
    "when treating graphs in linear algebra form\n",
    "is the **adjacency matrix**.\n",
    "For example, for four nodes joined in a chain:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import networkx as nx\n",
    "\n",
    "nodes = list(range(4))\n",
    "G1 = nx.Graph()\n",
    "G1.add_nodes_from(nodes)\n",
    "G1.add_edges_from(zip(nodes, nodes[1:]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "we can visualize the graph:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nx.draw(G1, with_labels=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "and we can visualize its adjacency matrix:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import nxviz as nv\n",
    "\n",
    "m = nv.matrix(G1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "and we can obtain the adjacency matrix as a NumPy array:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "A1 = nx.to_numpy_array(G1, nodelist=sorted(G1.nodes()))\n",
    "A1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Symmetry\n",
    "\n",
    "Remember that for an undirected graph,\n",
    "the adjacency matrix will be symmetric about the diagonal,\n",
    "while for a directed graph,\n",
    "the adjacency matrix will be _asymmetric_."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Path finding\n",
    "\n",
    "In the Paths chapter, we can use the breadth-first search algorithm\n",
    "_to find a shortest path between any two nodes_.\n",
    "\n",
    "As it turns out, using adjacency matrices, we can answer a related question,\n",
    "which is _how many paths exist of length K between two nodes_.\n",
    "\n",
    "To see how, we need to see the relationship between matrix powers and graph path lengths.\n",
    "\n",
    "Let's take the adjacency matrix above,\n",
    "raise it to the second power,\n",
    "and see what it tells us."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "np.linalg.matrix_power(A1, 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise: adjacency matrix power?\n",
    "\n",
    "> What do you think the values in the adjacency matrix are related to?\n",
    "> If studying in a group, discuss with your neighbors;\n",
    "> if working on this alone, write down your thoughts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from nams.solutions.linalg import adjacency_matrix_power\n",
    "from nams.functions import render_html\n",
    "\n",
    "render_html(adjacency_matrix_power())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Higher matrix powers\n",
    "\n",
    "The semantic meaning of adjacency matrix powers\n",
    "is preserved even if we go to higher powers.\n",
    "For example, if we go to the 3rd matrix power:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "np.linalg.matrix_power(A1, 3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You should be able to convince yourself that:\n",
    "\n",
    "1. There's no way to go from a node back to itself in 3 steps, thus explaining the diagonals, and \n",
    "1. The off-diagonals take on the correct values when you think about them in terms of \"ways to go from one node to another\"."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### With directed graphs?\n",
    "\n",
    "Does the \"number of steps\" interpretation hold\n",
    "with directed graphs?\n",
    "Yes it does!\n",
    "Let's see it in action."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "G2 = nx.DiGraph()\n",
    "G2.add_nodes_from(nodes)\n",
    "G2.add_edges_from(zip(nodes, nodes[1:]))\n",
    "nx.draw(G2, with_labels=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercise: directed graph matrix power\n",
    "\n",
    "> Convince yourself that the resulting adjacency matrix power\n",
    "> contains the same semantic meaning\n",
    "> as that for an undirected graph,\n",
    "> that is,\n",
    "> _the number of ways to go from \"row\" node to \"column\" node\n",
    "> in K steps_.\n",
    "> (I have provided three different matrix powers for you.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "A2 = nx.to_numpy_array(G2)\n",
    "np.linalg.matrix_power(A2, 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "np.linalg.matrix_power(A2, 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "np.linalg.matrix_power(A2, 4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Message Passing\n",
    "\n",
    "Let's now dive into the second topic here,\n",
    "that of message passing.\n",
    "\n",
    "To show how message passing works on a graph,\n",
    "let's start with the directed linear chain,\n",
    "as this will make things easier to understand.\n",
    "\n",
    "### \"Message\" representation in matrix form\n",
    "\n",
    "Our graph adjacency matrix contains nodes ordered in a particular fashion\n",
    "along the rows and columns.\n",
    "We can also create a \"message\" matrix $M$,\n",
    "using the same ordering of nodes along the rows,\n",
    "with columns instead representing a \"message\"\n",
    "that is intended to be \"passed\" from one node to another:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "M = np.array([1, 0, 0, 0])\n",
    "M"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice where the position of the value `1` is - at the first node.\n",
    "\n",
    "If we take M and matrix multiply it against A2, let's see what we get:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "M @ A2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The message has been passed onto the next node!\n",
    "And if we pass the message one more time:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "M @ A2 @ A2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, the message lies on the 3rd node!\n",
    "\n",
    "We can make an animation to visualize this more clearly. \n",
    "_There are comments in the code to explain what's going on!_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "def propagate(G, msg, n_frames):\n",
    "    \"\"\"\n",
    "    Computes the node values based on propagation.\n",
    "\n",
    "    Intended to be used before or when being passed into the\n",
    "    anim() function (defined below).\n",
    "\n",
    "    :param G: A NetworkX Graph.\n",
    "    :param msg: The initial state of the message.\n",
    "    :returns: A list of 1/0 representing message status at\n",
    "        each node.\n",
    "    \"\"\"\n",
    "    # Initialize a list to store message states at each timestep.\n",
    "    msg_states = []\n",
    "\n",
    "    # Set a variable `new_msg` to be the initial message state.\n",
    "    new_msg = msg\n",
    "\n",
    "    # Get the adjacency matrix of the graph G.\n",
    "    A = nx.to_numpy_array(G)\n",
    "\n",
    "    # Perform message passing at each time step\n",
    "    for i in range(n_frames):\n",
    "        msg_states.append(new_msg)\n",
    "        new_msg = new_msg @ A\n",
    "\n",
    "    # Return the message states.\n",
    "    return msg_states"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from IPython.display import HTML\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib import animation\n",
    "\n",
    "\n",
    "def update_func(step, nodes, colors):\n",
    "    \"\"\"\n",
    "    The update function for each animation time step.\n",
    "\n",
    "    :param step: Passed in from matplotlib's FuncAnimation. Must\n",
    "        be present in the function signature.\n",
    "    :param nodes: Returned from nx.draw_networkx_edges(). Is an\n",
    "        array of colors.\n",
    "    :param colors: A list of pre-computed colors.\n",
    "    \"\"\"\n",
    "    nodes.set_array(colors[step].ravel())\n",
    "    return nodes\n",
    "\n",
    "\n",
    "def anim(G, initial_state, n_frames=4):\n",
    "    \"\"\"\n",
    "    Animation function!\n",
    "    \"\"\"\n",
    "    # First, pre-compute the message passing states over all frames.\n",
    "    colors = propagate(G, initial_state, n_frames)\n",
    "    # Instantiate a figure\n",
    "    fig = plt.figure()\n",
    "    # Precompute node positions so that they stay fixed over the entire animation\n",
    "    pos = nx.kamada_kawai_layout(G)\n",
    "    # Draw nodes to screen\n",
    "    nodes = nx.draw_networkx_nodes(\n",
    "        G, pos=pos, node_color=colors[0].ravel(), node_size=20\n",
    "    )\n",
    "    # Draw edges to screen\n",
    "    ax = nx.draw_networkx_edges(G, pos)\n",
    "    # Finally, return the animation through matplotlib.\n",
    "    return animation.FuncAnimation(\n",
    "        fig, update_func, frames=range(n_frames), fargs=(nodes, colors)\n",
    "    )\n",
    "\n",
    "\n",
    "# Initialize the message\n",
    "msg = np.zeros(len(G2))\n",
    "msg[0] = 1\n",
    "\n",
    "# Animate the graph with message propagation.\n",
    "HTML(anim(G2, msg, n_frames=4).to_html5_video())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Bipartite Graphs & Matrices\n",
    "\n",
    "The section on message passing above assumed unipartite graphs, or at least graphs for which messages can be meaningfully passed between nodes. \n",
    "\n",
    "In this section, we will look at bipartite graphs. \n",
    "\n",
    "Recall from before the definition of a bipartite graph:\n",
    "\n",
    "- Nodes are separated into two partitions (hence 'bi'-'partite').\n",
    "- Edges can only occur between nodes of different partitions.\n",
    "\n",
    "Bipartite graphs have a natural matrix representation, known as the **biadjacency matrix**. Nodes on one partition are the rows, and nodes on the other partition are the columns.\n",
    "\n",
    "NetworkX's `bipartite` module provides a function for computing the biadjacency matrix of a bipartite graph."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's start by looking at a toy bipartite graph, a \"customer-product\" purchase record graph, with 4 products and 3 customers. The matrix representation might be as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Rows = customers, columns = products, 1 = customer purchased product, 0 = customer did not purchase product.\n",
    "cp_mat = np.array([[0, 1, 0, 0], [1, 0, 1, 0], [1, 1, 1, 1]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "From this \"bi-adjacency\" matrix, one can compute the projection onto the customers, matrix multiplying the matrix with its transpose."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "c_mat = cp_mat @ cp_mat.T  # c_mat means \"customer matrix\"\n",
    "c_mat"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What we get is the connectivity matrix of the customers, based on shared purchases. \n",
    "The diagonals are the degree of the customers in the original graph, \n",
    "i.e. the number of purchases they originally made, \n",
    "and the off-diagonals are the connectivity matrix, based on shared products."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get the products matrix, we make the transposed matrix the left side of the matrix multiplication."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "p_mat = cp_mat.T @ cp_mat  # p_mat means \"product matrix\"\n",
    "p_mat"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You may now try to convince yourself that the diagonals are the number of times a customer purchased that product, and the off-diagonals are the connectivity matrix of the products, weighted by how similar two customers are."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Exercises \n",
    "\n",
    "In the following exercises, you will now play with a customer-product graph from Amazon. This dataset was downloaded from [UCSD's Julian McAuley's website](http://jmcauley.ucsd.edu/data/amazon/), and corresponds to the digital music dataset.\n",
    "\n",
    "This is a bipartite graph. The two partitions are:\n",
    "\n",
    "- `customers`: The customers that were doing the reviews.\n",
    "- `products`: The music that was being reviewed.\n",
    "\n",
    "In the original dataset (see the original JSON in the `datasets/` directory), they are referred to as:\n",
    "\n",
    "- `customers`: `reviewerID`\n",
    "- `products`: `asin`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from nams import load_data as cf\n",
    "\n",
    "G_amzn = cf.load_amazon_reviews()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Remember that with bipartite graphs, it is useful to obtain nodes from one of the partitions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from nams.solutions.bipartite import extract_partition_nodes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "customer_nodes = extract_partition_nodes(G_amzn, \"customer\")\n",
    "mat = nx.bipartite.biadjacency_matrix(G_amzn, row_order=customer_nodes)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You'll notice that this matrix is extremely large! There are 5541 customers and 3568 products,\n",
    "for a total matrix size of $5541 \\times 3568 = 19770288$, but it is stored in a sparse format because only 64706 elements are filled in."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "mat"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example: finding customers who reviewed the most number of music items.\n",
    "\n",
    "Let's find out which customers reviewed the most number of music items.\n",
    "\n",
    "To do so, you can break the problem into a few steps.\n",
    "\n",
    "First off, we compute the customer projection using matrix operations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "customer_mat = mat @ mat.T"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, get the diagonals of the customer-customer matrix. Recall here that in `customer_mat`, the diagonals correspond to the degree of the customer nodes in the bipartite matrix.\n",
    "\n",
    "SciPy sparse matrices provide a `.diagonal()` method that returns the diagonal elements."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Get the diagonal.\n",
    "degrees = customer_mat.diagonal()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, find the index of the customer that has the highest degree."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "cust_idx = np.argmax(degrees)\n",
    "cust_idx"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can verify this independently by sorting the customer nodes by degree."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import janitor\n",
    "\n",
    "# There's some pandas-fu we need to use to get this correct.\n",
    "deg = (\n",
    "    pd.Series(dict(nx.degree(G_amzn, customer_nodes)))\n",
    "    .to_frame()\n",
    "    .reset_index()\n",
    "    .rename_column(\"index\", \"customer\")\n",
    "    .rename_column(0, \"num_reviews\")\n",
    "    .sort_values(\"num_reviews\", ascending=False)\n",
    ")\n",
    "deg.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Indeed, customer 294 was the one who had the most number of reviews!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example: finding similar customers\n",
    "\n",
    "Let's now also compute which two customers are similar, based on shared reviews. To do so involves the following steps:\n",
    "\n",
    "1. We construct a sparse matrix consisting of only the diagonals. `scipy.sparse.diags(elements)` will construct a sparse diagonal matrix based on the elements inside `elements`.\n",
    "1. Subtract the diagonals from the customer matrix projection. This yields the customer-customer similarity matrix, which should only consist of the off-diagonal elements of the customer matrix projection.\n",
    "1. Finally, get the indices where the weight (shared number of between the customers is highest. (*This code is provided for you.*)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import scipy.sparse as sp"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Construct diagonal elements.\n",
    "customer_diags = sp.diags(degrees)\n",
    "# Subtract off-diagonals.\n",
    "off_diagonals = customer_mat - customer_diags\n",
    "# Compute index of most similar individuals.\n",
    "np.unravel_index(np.argmax(off_diagonals), customer_mat.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Performance: Object vs. Matrices\n",
    "\n",
    "Finally, to motivate why you might want to use matrices rather than graph objects to compute some of these statistics, let's time the two ways of getting to the same answer."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Objects\n",
    "\n",
    "Let's first use NetworkX's built-in machinery to find customers that are most similar."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from time import time\n",
    "\n",
    "start = time()\n",
    "\n",
    "# Compute the projection\n",
    "G_cust = nx.bipartite.weighted_projected_graph(G_amzn, customer_nodes)\n",
    "\n",
    "# Identify the most similar customers\n",
    "most_similar_customers = sorted(\n",
    "    G_cust.edges(data=True), key=lambda x: x[2][\"weight\"], reverse=True\n",
    ")[0]\n",
    "\n",
    "end = time()\n",
    "print(f\"{end - start:.3f} seconds\")\n",
    "print(f\"Most similar customers: {most_similar_customers}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Matrices\n",
    "\n",
    "Now, let's implement the same thing in matrix form."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "start = time()\n",
    "\n",
    "# Compute the projection using matrices\n",
    "mat = nx.bipartite.matrix.biadjacency_matrix(G_amzn, customer_nodes)\n",
    "cust_mat = mat @ mat.T\n",
    "\n",
    "# Identify the most similar customers\n",
    "degrees = customer_mat.diagonal()\n",
    "customer_diags = sp.diags(degrees)\n",
    "off_diagonals = customer_mat - customer_diags\n",
    "c1, c2 = np.unravel_index(np.argmax(off_diagonals), customer_mat.shape)\n",
    "\n",
    "end = time()\n",
    "print(f\"{end - start:.3f} seconds\")\n",
    "print(\n",
    "    f\"Most similar customers: {customer_nodes[c1]}, {customer_nodes[c2]}, {cust_mat[c1, c2]}\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "On a modern PC, the matrix computation should be about 10-50X faster\n",
    "using the matrix form compared to the object-oriented form.\n",
    "(The web server that is used to build the book\n",
    "might not necessarily have the software stack to do this though,\n",
    "so the time you see reported might not reflect the expected speedups.)\n",
    "I'd encourage you to fire up a Binder session or clone the book locally \n",
    "to test out the code yourself.\n",
    "\n",
    "You may notice that it's much easier to read the \"objects\" code, \n",
    "but the matrix code way outperforms the object code. \n",
    "This tradeoff is common in computing, and shouldn't surprise you.\n",
    "That said, the speed gain alone is a great reason to use matrices!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Acceleration on a GPU\n",
    "\n",
    "If your appetite has been whipped up for even more acceleration\n",
    "and you have a GPU on your daily compute,\n",
    "then you're very much in luck!\n",
    "\n",
    "The [RAPIDS.AI](https://rapids.ai) project has a package called [cuGraph](https://github.com/rapidsai/cugraph),\n",
    "which provides GPU-accelerated graph algorithms.\n",
    "As over release 0.16.0, all cuGraph algorithms will be able to accept NetworkX graph objects!\n",
    "This came about through online conversations on GitHub and Twitter,\n",
    "which for us, personally, speaks volumes to the power of open source projects!\n",
    "\n",
    "Because cuGraph does presume that you have access to a GPU,\n",
    "and because we assume most readers of this book might not have access to one easily,\n",
    "we'll delegate teaching how to install and use cuGraph to the cuGraph devs and [their documentation][docs].\n",
    "Nonetheless, if you do have the ability to install and use the RAPIDS stack,\n",
    "definitely check it out!\n",
    "\n",
    "[docs]: https://docs.rapids.ai/api/cugraph/stable/api.html"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "nams",
   "language": "python",
   "name": "nams"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
